package com.prim.threadcoreknowledge.threadobjectclasscommonmethods;

public class WaitNotifyPrintOddEveWait {
    private static int count;

    private static final Object lock = new Object();

    static class TurningRuner implements Runnable {

        @Override
        public void run() {
            while (count < 100) {
                //当前线程获得锁
                System.out.println(Thread.currentThread().getState());
                synchronized (lock) {
                    System.out.println(Thread.currentThread().getName() + ":" + count++);
                    //唤醒另一个处于BLOCKED的线程
                    lock.notify();
                    if (count <= 100) {
                        try {
                            //如果任务还没有结束 就让出锁 自己休眠
                            lock.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
    }

    public static void main(String[] args) {
        new Thread(new TurningRuner(),"偶数").start();
        try {
            //因为先执行start并不一定先执行 所以休眠100ms
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        new Thread(new TurningRuner(),"奇数").start();
    }
}
